<?php

namespace app\api\controller\user;

use app\api\BaseController;
use app\api\service\UserService;
use Mrgoon\AliSms\AliSms;
use thans\jwt\facade\JWTAuth;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;

class UserController extends BaseController
{
    /**
     * 绑定手机号
     */
    public function bindPhone()
    {
        $param = $this->request->post();
        $user_id = $this->request->user['user_id'];
        try {
            validate('UserValidate.bindPhone')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $is_phone = Db::name('user_auth')
        ->where('id', $user_id)
        ->where('store_id', $param['store_id'])
        ->value('phone');
        if ($is_phone) {
            return json(['code' => 0, 'msg' => '手机号已存在，请勿重复绑定']);
        }

        $uid = Db::name('user_auth')
        ->where('phone', $param['phone'])
        ->where('store_id', $param['store_id'])
        ->value('id');
        if ($uid) {
            return json(['code' => 0, 'msg' => '手机号已存在']);
        }

        $userService = new UserService();
        $rst = $userService->bindPhone($param, $user_id);
        return $rst ? json(['code' => 1, 'msg' => '绑定成功!', 'data' => '']): json(['code' => 0, 'msg' => '绑定失败!', 'data' => '']);
    }

    /**
     * 忘记密码
     */
    public function forgetPassword()
    {
        $param = $this->request->post();
        try {
            validate('UserValidate.wjPassword')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $user_id = Db::name('user_auth')
            ->where('phone', $param['phone'])
            ->where('store_id', $param['store_id'])
            ->value('id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '账号不存在']);
        }

        $userService = new UserService();
        $rst = $userService->resetPassword($param, $user_id);
        return $rst ? json(['code' => 1, 'msg' => '设置成功!', 'data' => '']): json(['code' => 0, 'msg' => '设置失败!', 'data' => '']);
    }

    /**
     * 修改密码
     */
    public function modifyPassword()
    {
        $param = $this->request->post();
        $user_id = $this->request->user['user_id'];
        $u_info = Db::name('user_auth')
        ->where('store_id', $param['store_id'])
        ->where('id', $user_id)
        ->find();

        if (empty($u_info)) {
            return json(['code' => 0, 'msg' => '未找到指定用户']);
        }

        if (empty($u_info['phone'])) {
            return json(['code' => 0, 'msg' => '未绑定手机号,请先绑定手机号']);
        }
        $param['phone'] = $u_info['phone'];
        try {
            validate('UserValidate.modifyPassword')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }
       
        $userService = new UserService();

        if (!empty($u_info['password'])) {
            $result = password_verify($param['old_password'],$u_info['password']);
            if (!$result) {
                return json(['code' => 0, 'msg' => '原密码不正确']);
            }
        }
        $rst = $userService->resetPassword($param, $user_id);
        $token = JWTAuth::builder(['user_id' => $user_id]);
        return $rst ? json(['code' => 1, 'msg' => '修改成功!', 'data' => ['token' => $token]]): json(['code' => 0, 'msg' => '修改失败!', 'data' => '']);
    }

    /**
     * 用户登录
     * */
    public function login()
    {
        $param = $this->request->post();


        if (empty($param['auth_type'])){
            return  json(['code' => 0, 'msg' => '非法登录!']);
        }

        $userService = new UserService();
        switch ($param['auth_type']){
            case 'wx':
                try {
                    validate('UserValidate.wxLogin')->check($param);
                }catch(ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
               
                $user_id = $userService->wxLogin($param);
              
                $is_bind_phone = Db::name('user_auth')->where('id', $user_id)->value('phone');
                $is_bind_phone = $is_bind_phone?true:false;

                if (!empty($user_id)){
                    $token = JWTAuth::builder(['user_id' => $user_id]);
                    return json(['code' => 1, 'msg' => '微信登录成功!', 'data' => ['token' => $token, 'is_bind_phone'=>$is_bind_phone]]);
                }

                return  json(['code' => 0, 'msg' => '微信登录失败!']);

            case 'ali':
                try {
                    validate('UserValidate.aliLogin')->check($param);
                }catch(ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                $user_id = $userService->aliLogin($param);

                if (!empty($user_id)){
                    $token = JWTAuth::builder(['user_id' => $user_id]);
                    return json(['code' => 1, 'msg' => '支付宝登录成功!', 'data' => ['token' => $token]]);
                }

                return  json(['code' => 0, 'msg' => '支付宝登录失败!']);
            case 'phone':
                try {
                    validate('UserValidate.phoneLogin')->check($param);
                }catch(ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                $user = $userService->phoneLogin($param);

                if (empty($user)){
                    return  json(['code' => 0, 'msg' => '用户名或密码不正确!']);
                }

                $result = password_verify($param['password'],$user['password']);

                if ($result){
                    $token = JWTAuth::builder(['user_id' => $user['id']]);
                    return json(['code' => 1, 'msg' => '登录成功!', 'data' => ['token' => $token]]);
                }

                return  json(['code' => 0, 'msg' => '密码错误!']);
        }

        return  json(['code' => 0,'msg' => '登录失败!']);
    }

    /**
     * 手机号验证码登录
     */
    public function phoneCodeLogin()
    {
        $param = $this->request->post();
        $userService = new UserService();
        try {
            validate('UserValidate.phoneCodeLogin')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }
        $user_id = $userService->phoneCodeLogin($param);
        if (!empty($user_id)){
            $token = JWTAuth::builder(['user_id' => $user_id]);
            return json(['code' => 1, 'msg' => '登录成功!', 'data' => ['token' => $token]]);
        }
    }

    /**
     * 用户注册
     * */
    public function register(){

        $param = $this->request->post();

        try {
            validate('UserValidate.register')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }
        $userService = new UserService();
        $user_id = $userService->register($param);

        if (empty($user_id)){
            return  json(['code' => 0,'msg' => '注册失败!']);
        }

        $token = JWTAuth::builder(['user_id' => $user_id]);

        return json(['code' => 1, 'msg' => '注册成功!', 'data' => ['token' => $token]]);
    }

    /**
     * 忘记密码/修改密码 发送验证码
     * */
    public function authSms()
    {
        $param = $this->request->post();
        $user_id = $this->request->user['user_id'];
        try {
            validate('UserValidate.authSms')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $u_info = Db::name('user_auth')
        ->where('store_id', $param['store_id'])
        ->where('id', $user_id)
        ->find();

        if (empty($u_info)) {
            return json(['code' => 0, 'msg' => '未找到指定用户']);
        }

        if (empty($u_info['phone'])) {
            return json(['code' => 0, 'msg' => '未绑定手机号,请先绑定手机号']);
        }

        $aliSms = new AliSms();
        $config = [
            'access_key' => 'LTAI5t9ZJzkSGoTDixR1Cg6D',
            'access_secret' => 'pLNAIpi3JXtzhgaM8ouaZFFcVhe0Tb',
            'sign_name' => '鑫程科技',
        ];

        $code = Str::random(6,1);
        $key = $u_info['phone'].'-'.$param['store_id'];

        try {
            $aliSms->sendSms($u_info['phone'], 'SMS_228280139', ['code'=> $code], $config);
        } catch (\Exception $e){
            return  json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        Cache::set($key,$code,300);


        return  json(['code' => 1, 'msg' => '短信发送成功!']);
    }

    /**
     * 发送短信
     * */
    public function sms()
    {
        $param = $this->request->post();
        try {
            validate('UserValidate.sms')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }


        $aliSms = new AliSms();
        $config = [
            'access_key' => 'LTAI5t9ZJzkSGoTDixR1Cg6D',
            'access_secret' => 'pLNAIpi3JXtzhgaM8ouaZFFcVhe0Tb',
            'sign_name' => '鑫程科技',
        ];

        $code = Str::random(6,1);
        $key = $param['phone'].'-'.$param['store_id'];

        try {
            $aliSms->sendSms($param['phone'], 'SMS_228280139', ['code'=> $code], $config);
        } catch (\Exception $e){
            return  json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        Cache::set($key,$code,300);


        return  json(['code' => 1, 'msg' => '短信发送成功!']);
    }


}